package com.zz.hhbl.ui.ai

import android.R.attr.onClick
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.shape.MaterialShapeDrawable
import com.google.android.material.shape.ShapeAppearanceModel
import com.google.android.material.shape.ShapePath
import com.google.android.material.shape.TriangleEdgeTreatment
import com.ss.bytertc.engine.type.MediaStreamType
import com.zz.framework.core.adapter.KotlinAdapter
import com.zz.framework.core.adapter.ViewBindingHolder
import com.zz.framework.core.event.FinishAiEvent
import com.zz.framework.core.ext.dp
import com.zz.framework.core.ext.gone
import com.zz.framework.core.ext.onClick
import com.zz.framework.core.ext.onDownOrUpEvent
import com.zz.framework.core.ext.scrollToPositionWithOffset
import com.zz.framework.core.ext.toLanguage
import com.zz.framework.core.ext.viewBinding
import com.zz.framework.core.ext.visibility
import com.zz.framework.core.utils.MediaPlayerUtils
import com.zz.framework.core.utils.language.Strings
import com.zz.framework.core.xdialog.XDialog
import com.zz.framework.core.xdialog.listener.OnBindViewListener
import com.zz.hhbl.R
import com.zz.hhbl.config.GlobalCache
import com.zz.hhbl.databinding.ActivityAiBinding
import com.zz.hhbl.databinding.DialogSwitchVoiceToneBinding
import com.zz.hhbl.databinding.ItemSwitchVoiceToneBinding
import com.zz.hhbl.entity.AiSubtitleEntity
import com.zz.hhbl.entity.DigitalHumanEntity
import com.zz.hhbl.utils.itemdecoration.RecyclerViewDivider
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.Subscribe


/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/2/28 14:28.
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 */
@AndroidEntryPoint
class AiActivity : BaseAiActivity() {
    val binding: ActivityAiBinding by viewBinding()
    lateinit var mAdapter: MessageAdapter
    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        binding.apply {
            showTopPop()
            btnVoice.apply {
                setText(Strings.音色.toLanguage())
                onClick {
                    showSwitchVoiceToneDialog()
                }
            }
            //禁麦
            rtcRoom?.unpublishStream(MediaStreamType.RTC_MEDIA_STREAM_TYPE_AUDIO)
            ivHoldToSpeak.onDownOrUpEvent {
                tvTipPop.gone()
                if (it) {
                    updateVoiceChat(handleType = 1)
                    //开麦
                    rtcRoom?.publishStream(MediaStreamType.RTC_MEDIA_STREAM_TYPE_AUDIO)
                    startVoiceWaveView()
                } else {
                    //禁麦
                    rtcRoom?.unpublishStream(MediaStreamType.RTC_MEDIA_STREAM_TYPE_AUDIO)
                    stopVoiceWaveView()
                }
            }
            btnBack.onClick {
                leaveRoom()
                stopVoiceChat()
            }
//            ivHangUp.onClick {
//                if (isLeave) {
//                    joinRoom(roomId, userId)
//                    startVoiceChat()
//                } else {
//                    leaveRoom()
//                    stopVoiceChat2()
//                    timer.cancel()
//                }
//            }
            recyclerView.layoutManager = LinearLayoutManager(this@AiActivity)
            recyclerView.adapter = MessageAdapter().also {
                mAdapter = it
            }
        }
        binding.ivAiName.text = Strings.欢欢.toLanguage()
    }


    private fun showTopPop() {
        val shapeModel = ShapeAppearanceModel.builder()
            .setAllCornerSizes(6f.dp())
            .setBottomEdge(
                object : TriangleEdgeTreatment(8f.dp(), false) {
                    override fun getEdgePath(
                        length: Float,
                        center: Float,
                        interpolation: Float,
                        shapePath: ShapePath
                    ) {
                        super.getEdgePath(length, center, interpolation, shapePath)
                    }
                }
            )
            .build()
        val backgroundDrawable = MaterialShapeDrawable(shapeModel).apply {
            setTint(Color.parseColor("#3D83FF"))
            paintStyle = Paint.Style.FILL
        }
        binding.tvTipPop.text = Strings.按住说话.toLanguage()
        binding.tvTipPop.background = backgroundDrawable
    }


    var mVoiceToneAdapter: KotlinAdapter<DigitalHumanEntity, ItemSwitchVoiceToneBinding>? = null
    fun showSwitchVoiceToneDialog() {
        XDialog.Builder(supportFragmentManager)
            .setViewBinding(DialogSwitchVoiceToneBinding::class.java) //设置弹窗展示的xml布局
            .setScreenWidthAspect(this, 1f)
            .setScreenHeightAspect(this, 0.7f)
            .setGravity(Gravity.BOTTOM) //设置弹窗展示位置
            .setTag("VoiceDialog")
            .setDimAmount(0.8f) //设置弹窗背景透明度(0-1f)
            .setCancelableOutside(true) //弹窗在界面外是否可以点击取消
            .setDialogAnimationRes(R.style.animate_dialog) //设置弹窗动画
            .setOnDismissListener {
                mVoiceToneAdapter = null
            }
            .setOnBindViewListener(object : OnBindViewListener<DialogSwitchVoiceToneBinding> {
                override fun onBind(itemBinding: DialogSwitchVoiceToneBinding, xDialog: XDialog) {
                    itemBinding.recyclerView.apply {
                        adapter = KotlinAdapter.Builder<DigitalHumanEntity, ItemSwitchVoiceToneBinding>(ItemSwitchVoiceToneBinding::class.java)
                            .addBindView { holder, item ->
                                holder.binding.apply {
                                    tvName.text = item?.name.orEmpty()
                                    ivSelect.visibility(item?.vioceCode == GlobalCache.aiVoiceTone)
                                }
                            }
                            .onItemClick { holder, item ->
                                item?.let {
                                    GlobalCache.aiVoiceTone = it.vioceCode.orEmpty()
                                    mVoiceToneAdapter?.notifyDataSetChanged()
                                    joinRoom(roomId, userId)
                                    startVoiceChat()
                                    xDialog.dismissNow()
                                    rtcRoom?.unpublishStream(MediaStreamType.RTC_MEDIA_STREAM_TYPE_AUDIO)
                                }
                            }
                            .setNewData(GlobalCache.getDigitalHuman())
                            .create().also { mVoiceToneAdapter = it }
                        layoutManager = GridLayoutManager(this@AiActivity, 2)
                        addItemDecoration(
                            RecyclerViewDivider.grid().dividerSize(15.dp())
                                .includeEdge()
                                .build()
                        )
                    }
                }
            })
            .setOnKeyListener { dialog, keyCode, event ->
                false
            }
            .create() //创建TDialog
            .show() //展示
    }

    override fun initObserver() {
        viewModel.stopVoiceChatLiveData.observe(this) {
            finish()
        }
        viewModel.stopVoiceChatLiveData2.observe(this) {
            isLeave = true
        }
        viewModel.startVoiceChatLiveData.observe(this) {
            isLeave = false
        }
    }


    fun startVoiceWaveView() {
        binding.voiceWaveViewLeft.apply {
            lineWidth = 5f.dp()
            lineSpace = 5f.dp()
            addBody(27)
            addBody(17)
            addBody(38)
            addBody(91)
            addBody(38)
            addBody(24)
            addBody(8)
            addBody(60)
            start()
        }
        binding.voiceWaveViewRight.apply {
            lineWidth = 5f.dp()
            lineSpace = 5f.dp()
            addBody(27)
            addBody(17)
            addBody(38)
            addBody(91)
            addBody(38)
            addBody(24)
            addBody(8)
            addBody(60)
            start()
        }
    }

    fun stopVoiceWaveView() {
        binding.voiceWaveViewLeft.clear()
        binding.voiceWaveViewRight.clear()
    }

    override fun getAiType(): String {
        return "dialogueAI"
    }

    override fun getToneType(): String {
        return GlobalCache.aiVoiceTone
    }

    override fun onTimerFinish() {
        GlobalCache.getDigitalHuman().filter { TextUtils.equals(it.vioceCode, getToneType()) }.firstOrNull()?.let {
            it.quitAudioUrl?.let { quitAudioUrl ->
                MediaPlayerUtils.getInstance().playAudioByUrl(quitAudioUrl, listener = {
                    leaveRoom()
                    stopVoiceChat()
                })
            }
        }
    }

    override fun onMessageReceived(message: AiSubtitleEntity) {
        mAdapter.addData(message)
        binding.recyclerView.scrollToPositionWithOffset(mAdapter.datas.size - 1)
    }

    @Subscribe
    fun onMessageReceived(message: FinishAiEvent) {
        leaveRoom()
        stopVoiceChat()
    }


    override fun onStop() {
        super.onStop()
        MediaPlayerUtils.getInstance().stop()
    }

    override fun onDestroy() {
        super.onDestroy()
    }


    private fun stopVoiceChat2() {
        viewModel.stopVoiceChat2()
    }


    override fun onPowerConnected(isCharging: Boolean) {
        leaveRoom()
        stopVoiceChat()
        super.onPowerConnected(isCharging)
    }


}